import java.util.List;
import java.util.*;

public class Test {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public List<Integer> preorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        while(!stack.isEmpty()||cur!=null) {
            while(cur!=null) {
                list.add(cur.val);
                stack.add(cur);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            cur = top.right;
        }

        return list;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        while(!stack.isEmpty() || cur!=null) {
            while(cur!=null) {
                stack.add(cur);
                cur = cur.left;
            }

            TreeNode top = stack.pop();
            list.add(top.val);
            cur = top.right;
        }

        return list;
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while(!stack.isEmpty() || cur!=null) {
            while(cur!=null) {
                stack.add(cur);
                cur = cur.left;
            }

            TreeNode top = stack.peek();
            if(top.right==null || top.right == prev) {
                list.add(top.val);
                stack.pop();
                prev = top;
            }else {
                cur = top.right;
            }
        }
        return list;
    }
}
